from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import time
import os
from datetime import datetime

class WebAutoExplorer:
    def __init__(self, browser="chrome"):
        """初始化配置"""
        self.driver = self._init_browser(browser)
        self.wait = WebDriverWait(self.driver, 30)
        self.screenshot_dir = f"screenshots_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        self.visited_pages = set()  # 记录已访问页面# 创建截图目录
        os.makedirs(self.screenshot_dir, exist_ok=True)
    def _init_browser(self, browser_type):
        """初始化浏览器"""
        if browser_type == "firefox":
            return webdriver.Firefox()
        elif browser_type == "edge":
            return webdriver.Edge()
        else:
                options = webdriver.ChromeOptions()
                options.add_argument("--start-maximized")
                return webdriver.Chrome(options=options)
    def login(self, url, username, password):
        """登录系统（需根据实际系统调整）"""
        print(f"🌐 正在登录系统: {url}")
        self.driver.get(url)
        time.sleep(10)
        # driver.get("https://www.hao123.com/")
        input_elements = self.driver.find_elements(By.CSS_SELECTOR, "[placeholder='请输入您的用户名']")
        input_elements[0].send_keys(username)
        # 定位用户名和密码输入框
        input_elements = self.driver.find_elements(By.CSS_SELECTOR, "[placeholder='请输入您的密码']")
        input_elements[0].send_keys(password)
        btn = self.driver.find_elements(By.TAG_NAME, "button")
        btn[0].click()
        time.sleep(2)
        #菜单
        menu_items = self.driver.find_elements(By.ID,"side-menu")
        menu_items[2].click()
    def _take_screenshot(self, name, subdir=""):
        """截图并保存到指定子目录"""
        dir_path = os.path.join(self.screenshot_dir, subdir)
        if not os.path.exists(dir_path):
                os.makedirs(dir_path)
        filename = f"{dir_path}/{name}_{datetime.now().strftime('%H%M%S')}.png"
        self.driver.save_screenshot(filename)
        print(f"📸 截图保存: {filename}")
        return filename
    def _get_menus(self):
        """获取所有顶级菜单（需根据实际系统调整）"""
        return self.driver.find_elements(By.CSS_SELECTOR, ".el-menu > .el-submenu")
    def _get_submenus(self, parent_menu):
        """获取子菜单（需根据实际系统调整）"""
        return parent_menu.find_elements(By.CSS_SELECTOR, ".el-menu--inline > .el-menu-item")
    def _click_safe(self, element):
        """安全点击元素（处理各种异常）"""
        try:
            self.driver.execute_script("arguments[0].scrollIntoViewIfNeeded();", element)
            element.click()
            time.sleep(1)
            # 等待操作生效
            return True
        except Exception as e:
            print(f"⚠️ 点击失败: {str(e)}")
            return False
    def _find_and_click_buttons(self):
        """查找并点击页面中的操作按钮"""# 常见操作按钮选择器（可根据实际系统添加）
        action_buttons = [
                ("新增按钮", ".el-button--primary", "新增|添加|创建"),
                ("编辑按钮", ".el-button--warning", "编辑|修改"),
                ("删除按钮", ".el-button--danger", "删除|移除")
        ]
        clicked = False
        for btn_type, btn_selector, btn_text_pattern in action_buttons:
            try:
                buttons = self.driver.find_elements(By.CSS_SELECTOR, btn_selector)
                for btn in buttons:
                    if btn.is_displayed() and btn.is_enabled():
                        btn_text = btn.text.strip()
                        if any(keyword in btn_text for keyword in btn_text_pattern.split("|")):
                            print(f"🖱️ 正在点击 [{btn_type}]: {btn_text}")
                            if self._click_safe(btn):
                                self._handle_dialog(btn_type)
                                clicked = True
                                time.sleep(1)  # 等待对话框打开
            except Exception as e:
                print(f"⚠️ 按钮操作异常: {str(e)}")
        return clicked
    def _handle_dialog(self, dialog_type):
        """处理弹出的对话框"""
        try:# 等待对话框出现
            dialog = self.wait.until(
                EC.visibility_of_element_located((By.CSS_SELECTOR, ".el-dialog__wrapper"))
            )
            # 对话框截图
            self._take_screenshot(f"{dialog_type}_对话框", "dialogs")
            # 关闭对话框（根据实际系统调整）
            close_btn = dialog.find_element(By.CSS_SELECTOR, ".el-dialog__headerbtn")
            self._click_safe(close_btn)
            time.sleep(0.5)
        except TimeoutException:
            print("⏳ 未检测到对话框弹出")
        except Exception as e:
            print(f"⚠️ 对话框处理失败: {str(e)}")
    def _explore_page(self, menu_path):
        """探索当前页面的所有功能"""# 当前页面截图
        page_hash = hash(">".join(menu_path))
        if page_hash not in self.visited_pages:
            self._take_screenshot("_".join(menu_path), "pages")
            self.visited_pages.add(page_hash)
            # 查找并点击操作按钮
            self._find_and_click_buttons()
    def traverse_system(self):
        """主遍历逻辑"""
        try:# 遍历顶级菜单
                top_menus = self._get_menus()
                for top_idx, top_menu in enumerate(top_menus):
                    top_name = top_menu.find_element(By.CSS_SELECTOR, ".el-submenu__title").text.strip()
                    print(f"\n🔍 进入顶级菜单: {top_name}")
                    # 展开顶级菜单
                    if not self._click_safe(top_menu):
                        continue# 遍历子菜单
                    sub_menus = self._get_submenus(top_menu)
                    for sub_idx, sub_menu in enumerate(sub_menus):
                        sub_name = sub_menu.text.strip()
                        menu_path = [top_name, sub_name]
                        print(f"  ➔ 进入子菜单: {sub_name}")
                        # 点击子菜单
                        if self._click_safe(sub_menu):# 等待页面加载完成（根据实际系统调整）
                          self.wait.until(
                                EC.presence_of_element_located((By.CSS_SELECTOR, ".main-content"))
                            )
                            # 探索当前页面
                        self._explore_page(menu_path)
        except Exception as e:
            print(f"❌ 遍历过程中出错: {str(e)}")
        finally:
            self.driver.quit()

if __name__ == "__main__":# 配置参数（需替换为实际值）
    config = {"url": "https://dengji.ruanzhu.me/onlinerun?hash=1d8ee7698a74ccbd98b8cb314987c96b79a1b29ff6d9d47f2ea6e6de83f9dad1#/login",
              "username": "admin","password": "123456","browser": "chrome"  # chrome/firefox/edge
    }
    # 执行自动化探索
    explorer = WebAutoExplorer()
    explorer.login(config["url"], config["username"], config["password"])
    explorer.traverse_system()